<template>
  <div class="flex flex-col h-full">
    <SearchContainer show-export @reset="() => formRef.resetFields()" @search="getData" @export="exportRef.$el.querySelector('button').click()">
      <a-form ref="formRef" class="form-style-flex" :model="formState" :label-col="{ style: { width: '80px' } }">
        <a-form-item name="dateRange" label="挂号日期">
          <a-range-picker v-model:value="formState.dateRange" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </a-form-item>
        <a-form-item name="docker" label="医生">
          <SelectTable :value="formState.empName" class-name="w-[240px]" type="医生" @select="onSelectDoctor" />
        </a-form-item>
      </a-form>
    </SearchContainer>
    <a-card class="flex-1">
      <a-space ref="exportRef" class="hidden">
        <BaseExport type="报表" name="实收金额统计" code="MAP000446" is-show-time :search-params="formState">导出</BaseExport>
      </a-space>
      <BaseTable
        v-if="columns.length && !loading"
        row-key="序号"
        :scroll="{ x: columns.length * 130 }"
        :loading="loading"
        :data-source="tableData"
        fill
        :columns="columns"
      >
        <!-- <template #bodyCell="{ column, index }">
          <template v-if="column.dataIndex === 'xh'">
            {{ index + 1 }}
          </template>
        </template> -->
      </BaseTable>
    </a-card>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import dayjs from 'dayjs'
import SearchContainer from '@/components/SearchContainer'
import BaseTable from '@/components/BaseTable'
import { formatAmount } from '@/utils/format.js'

const exportRef = ref(null)
const formRef = ref(null)
const formState = ref({
  dateRange: [dayjs().subtract(30, 'day').format('YYYY-MM-DD'), dayjs().format('YYYY-MM-DD')]
})
const columns = ref([])
const { loading, tableData, getData } = useTable({
  url: '/statistic/getStatisticstheAmountReceived',
  params: formState.value,
  pagination: false,
  immediate: true,
  onSuccess: (res) => {
    if (res && res.length > 0) {
      const idx = findObjectWithMostKeyValuePairs(res)
      columns.value = Object.keys(res[idx]).map((item) => {
        const align = typeof res[0][item] === 'number' || item.indexOf('金额') > -1 || item.indexOf('费') > -1 ? 'right' : 'left'
        const width = item === '序号' ? 60 : ''
        const customRender = item.indexOf('金额') > -1 || item.indexOf('费') > -1 ? ({ text }) => formatAmount(text, 2) : null
        return { title: item, dataIndex: item, customRender, align: item === '序号' ? 'left' : align, ellipsis: true, width }
      })
      const columnsTitle = columns.value.map((item) => item.title)
      const obj = {}
      columnsTitle.forEach((item) => {
        if (item !== '序号' && item !== '医生工号' && item !== '医生姓名') {
          obj[item] = tableData.value.reduce((accumulator, currentItem) => {
            if (currentItem[item]) {
              return Number(accumulator) + Number(currentItem[item])
            } else {
              return Number(accumulator)
            }
          }, 0)
          obj[item] = formatAmount(obj[item])
        }
      })
      tableData.value.push({ 医生姓名: '合计', ...obj })
    }
  }
})

const onSelectDoctor = (select) => {
  formState.value.zjm = select.empId
  formState.value.empName = select.empName
}
const findObjectWithMostKeyValuePairs = (arr) => {
  const arrObj = []
  arr.forEach((item, index) => {
    arrObj.push({ num: Object.keys(item).length, idx: index })
  })
  const max = arrObj.sort((a, b) => b.num - a.num)[0].idx // 40
  return max // 返回键值对最多的对象
}
</script>
